package com.zz.server.handle.defaults;

import com.zz.common.annotation.Executor;
import com.zz.common.config.Constants;
import com.zz.common.entity.Information;
import com.zz.common.enums.MessageType;
import com.zz.common.handle.executor.AbstractMessageExecutor;
import com.zz.common.protocol.DefaultProtocol;
import com.zz.common.utils.ObjectUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * 连接失败消息
 */
@Slf4j
@Executor(msgType = MessageType.CONNECT_FAIR)
public class ConnectFairExecutor extends AbstractMessageExecutor {

    @Override
    public void execute(Information information) {
        ChannelHandlerContext context = information.getContext();
        DefaultProtocol protocol = (DefaultProtocol) information.getProtocolMsg();
        log.error("connect fair, error info: {}", protocol.getMeta().getErrorInfo());

        // 关闭客户端
        Map<String, Channel> channelCache = context.channel().attr(Constants.Attributes.CHANNEL_CACHE).get();
        if (ObjectUtil.isNull(channelCache) || channelCache.isEmpty() || channelCache.containsKey(protocol.getMeta().getLocalChannelId())) {
            log.error("connect fair, local channel is null");
            return;
        }
        Channel localChannel = channelCache.get(protocol.getMeta().getLocalChannelId());
        ObjectUtil.setFieldNull(localChannel, Constants.Attributes.SERVER_CHANNEL);
        localChannel.close();
    }
}
